package com.cscj.android.repository.repo.favorites

import android.graphics.Bitmap
import com.cscj.android.repository.db.dao.FavoritesDao
import com.cscj.android.repository.db.entity.FavoritesEntity
import com.cscj.android.utils.BitmapUtils.asBase64String
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.Date

class FavoritesRepositoryImpl : FavoritesRepository, KoinComponent {

    private val favoritesDao by inject<FavoritesDao>()

    override suspend fun init() {
        favoritesDao.addFavorites(
            FavoritesEntity(
                id = FavoritesEntity.RootId,
                type = FavoritesEntity.TYPE_ROOT,
                title = "收藏夹",
                addDate = Date(),
                url = "收藏夹"
            )
        )
    }

    override suspend fun favoriteLink(title: String, url: String, favicon: Bitmap?) {
        favoritesDao.addFavorites(
            FavoritesEntity(
                type = FavoritesEntity.TYPE_ITEM,
                title = title,
                addDate = Date(),
                icon = favicon?.asBase64String(),
                url = url
            )
        )
    }

    override fun allFavorites(): Flow<List<FavoritesEntity>> {
        return favoritesDao.allFavorites()
    }

    override fun favorites(keyword: String?): Flow<List<FavoritesEntity>> {
        return if (keyword.isNullOrBlank()) {
            favoritesDao.favorites()
        } else {
            favoritesDao.favorites("%$keyword%")
        }
    }

    override suspend fun deleteByIds(ids: IntArray) {
        favoritesDao.deleteByIds(ids)
    }

    override fun checkUrlFavorite(url: String): Flow<Boolean> {
        return favoritesDao.favoriteCount(url).map {
            it > 0
        }
    }

    override suspend fun deleteByUrl(url: String) {
        favoritesDao.deleteByUrl(url)
    }

    override suspend fun updateFavicon(url: String, favicon: Bitmap?) {
        favoritesDao.updateFavicon(url, favicon?.asBase64String())
    }
}